<?php
/**
 * Created by PhpStorm.
 * User: dell
 * Date: 2017/6/9
 * Time: 10:12
 */

namespace Home\Logic\Controller;
use Home\Model\UserModel;
use Think\Controller;
use WeiChat\api\WeixinApi;

class MainController extends Controller {
    /**
     * @var WeixinApi
     */
    protected $weixinObj = null;
    /**
     * @var UserModel
     */
    protected $userModel = null;
    public function _initialize(){
        $this->weixinObj = WeixinApi::getInstance();
        if($this->userModel == null){
            $this->userModel = new UserModel();
        }
        if(!$this->checkUser()){
            $this->getWeiChatUser(__ACTION__);
        }
    }
    protected function checkUser(){
        if(session('openid')){
            $this->weixinObj->openid = session('openid');
            return true;
        }
        return false;
    }
    public function getWeiChatUser($url){
        $res = $this->weixinObj->getOpenId(WEB_URL.U('Index/getWeiChatUser'),$url);
        $state = I('get.state');
        session('openid',$res['openid']);
        $this->userModel->addWeiChatUser($res);
        header("Location: ".U($state));exit();
    }
}